﻿using System;
using System.Text.RegularExpressions;
using CourseManager.Model.Exception;

namespace CourseManager.Model
{
	public enum WeekType
	{
		Odd, Even, Both
	}

	public class TimeInfo
	{
		public static readonly string Pattern = @"(一|二|三|四|五|六|日)[01]?\d-[01]?\d(单|双)?";

	    
		public static readonly string[] Days = {"一", "二", "三", "四", "五", "六", "日"};

		public int Start { get; set; }
		public int End { get; set; }
		public int Day { get; set; }
		public WeekType Type { get; set; }
	
		public TimeInfo(String time)//一1-2单
		{
			if(!Regex.IsMatch(time, Pattern))
				throw new CMException(string.Format("Argument[{0}] is wrong format", time));
			string day = time.Substring(0, 1);
			for(var i = 0; i < Days.Length; ++i)
				if(day.Equals(Days[i]))
				{
					Day = i + 1;
					break;
				}

			if(time.EndsWith("单"))
			{
				Type = WeekType.Even;
				time = time.Substring(0, time.Length - 1);
			}
			else if(time.EndsWith("双"))
			{
				Type = WeekType.Odd;
				time = time.Substring(0, time.Length - 1);
			}
			else
			{
				Type = WeekType.Both;
			} 
			
			var no = time.Substring(1, time.Length - 1);
			var num = no.Split('-');
			Start = Int32.Parse(num[0]) - 1;
			End = Int32.Parse(num[1]) - 1;
		}

		public bool IntersectWith(TimeInfo other)
		{
			if(Day != other.Day) return false;
			if(End < other.Start || Start > other.End) return false;
			if(other.Type == WeekType.Both && Type == WeekType.Both) return true;
			return other.Type.Equals(this);
		}
	}
	
	
}
